package com.xmutca.notify.router.handler;

import com.alibaba.fastjson.JSON;
import com.xmutca.core.common.Result;
import com.xmutca.core.netty.api.*;
import com.xmutca.core.websocket.handler.TextWebSocketFrameHandler;
import com.xmutca.core.websocket.handler.WebSocketEventHandler;
import com.xmutca.sso.api.Account;
import com.xmutca.sso.api.server.AccountService;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**
 * @author: 彭伟煌(pengweihuang@xmutca.com)
 * @create: 2016-08-15 22:06
 */
public class NotifyEventHandler extends WebSocketEventHandler {

    private AccountService accountService;

    /**
     * 打开连接事件
     * @param handler
     * @param userId
     */
    public void open(TextWebSocketFrameHandler handler, String userId) {
        //广播大家
        Result<Account> account = accountService.getById(userId);
        String username = userId;
        if (account.getResult() != null) {
            username = account.getResult().getUsername();
        }
        broadcastMessage(handler, String.format("用户%s加入了聊天组", username));
    }

    /**
     * 关闭连接事件
     * @param handler
     * @param userId
     */
    public void close(TextWebSocketFrameHandler handler, String userId) {
        //广播大家
        Result<Account> account = accountService.getById(userId);
        String username = userId;
        if (account.getResult() != null) {
            username = account.getResult().getUsername();
        }
        broadcastMessage(handler, String.format("用户%s离开了聊天组", username));
    }

    /**
     * 接收数据事件
     * @param handler
     * @param message
     */
    public void receive(TextWebSocketFrameHandler handler, String from, String message) {
        if (!StringUtils.hasText(message)) {
            notifyMessage(handler, from, "非法的消息类型");
            return;
        }

        Message msg = JSON.parseObject(message, Message.class);
        if (msg.getMsgType() == null) {
            notifyMessage(handler, from, "非法的消息类型");
            return;
        }

        String to = msg.getTo();
        if (!StringUtils.hasText(to)) {
            notifyMessage(handler, from, "非法的消息类型");
            return;
        }

        //消息类型转换
        if (Message.MessageType.link == msg.getMsgType()) {
            msg = JSON.parseObject(message, LinkMessage.class);
        } else if (Message.MessageType.text == msg.getMsgType()) {
            msg = JSON.parseObject(message, TextMessage.class);
        } else if (Message.MessageType.picture == msg.getMsgType()) {
            msg = JSON.parseObject(message, PictureMessage.class);
        } else if (Message.MessageType.position == msg.getMsgType()) {
            msg = JSON.parseObject(message, PositionMessage.class);
        } else if (Message.MessageType.voice == msg.getMsgType()) {
            msg = JSON.parseObject(message, VoiceMessage.class);
        } else if (Message.MessageType.video == msg.getMsgType()) {
            msg = JSON.parseObject(message, VideoMessage.class);
        }

        //设置消息的id与消息的时间
        msg.setMsgId(UUID.randomUUID().toString());
        msg.setTimestamp(System.currentTimeMillis());

        //通知自己
        notifyMessage(handler, from, "消息已到达");
        //发送消息
        sendMessage(handler, from, to, msg);
    }

    /**
     * 发送消息
     * @param handler
     * @param from
     * @param to
     * @param msg
     */
    void sendMessage(TextWebSocketFrameHandler handler, String from, String to, Message msg) {
        msg.setFrom(from);
        msg.setTo(to);

        //设定相关的用户名
        Result<Account> fromAccount = accountService.getById(from);
        if (fromAccount.getResult() != null) {
            msg.setFromUsername(fromAccount.getResult().getUsername());
        }
        Result<Account> toAccount = accountService.getById(to);
        if (toAccount.getResult() != null) {
            msg.setToUsername(toAccount.getResult().getUsername());
        }
        handler.sendMessage(to, msg.toString());
    }

    /**
     * 通知消息，通知自己
     * @param handler
     * @param from
     * @param msg
     * @param broadcast
     */
    void notifyMessage(TextWebSocketFrameHandler handler, String from, String msg, boolean broadcast) {
        NotifyMessage notify = new NotifyMessage();

        if (broadcast) {
            notify.setBroadcastStatus();
        }

        notify.setMessage(msg);
        sendMessage(handler, from, from, notify);
    }

    /**
     * 通知消息，通知自己
     * @param handler
     * @param from
     * @param msg
     */
    void notifyMessage(TextWebSocketFrameHandler handler, String from, String msg) {
        notifyMessage(handler, from, msg, false);
    }

    /**
     * 广播消息，广播全部人
     * @param handler
     * @param msg
     */
    void broadcastMessage(TextWebSocketFrameHandler handler, String msg) {
        notifyMessage(handler, null, msg, true);
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}
